<template>
  <Drawer :title="title" v-model="show" width="720" :mask-closable="false"
          @on-close="closeWin"
          :styles="{ height: 'calc(100% - 55px)', overflow: 'auto', paddingBottom: '53px', position: 'static' }">
    <Form :model="formData" ref="validForm" :rules="ruleValidate">
      <FormItem  label-position="top" prop="url" :error="error.url">
        <Row :gutter="32">
          <Col span="18">
            <Upload
                ref="upload"
                :show-upload-list="false"
                :format="['jpg','jpeg','png']"
                :max-size="20480"
                name="swiper"
                accpet="image/*"
                :headers="{Authorization: 'Bearer ' + $store.state.token}"
                :default-file-list="defaultList"
                type="drag" :on-success="handleSuccess"
                :action="$api.updateAdvertPath()"> <!-- 设置上传广告图后台地址 -->
              <div style="padding: 20px 0">
                <Icon type="ios-camera" size="52" style="color: #3399ff"></Icon>
                <p>请选择要上传的广告图</p>
              </div>
            </Upload>
          </Col>
          <Col span="6">
            <div class="demo-upload-list" v-for="item in uploadList">
              <template v-if="item.status === 'finished'">
                <Image :src="item.url" fit="cover" width="100%" height="100%"/>
              </template>
              <template v-else>
                <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
              </template>
            </div>
          </Col>
        </Row>
      </FormItem>

      <FormItem label="系统名" label-position="top" prop="sysId" :error="error.sysId">
        <Select v-model.number="formData.sysId" placeholder="请选择所属系统">
          <Option v-for="item in sysList" :value="item.id" :key="item.id">{{ item.sysName }}</Option>
        </Select>
      </FormItem>

      <FormItem label="链接地址" label-position="top" prop="linkUrl" :error="error.linkUrl">
        <Input v-model="formData.linkUrl" placeholder="请输入链接地址"/>
      </FormItem>

      <FormItem label="状态" label-position="top" prop="state" :error="error.state">
        <Switch size="large" v-model="formData.state">
          <template #open>
            <span>启用</span>
          </template>
          <template #close>
            <span>禁用</span>
          </template>
        </Switch>
      </FormItem>
    </Form>

    <div class="demo-drawer-footer">
      <Button style="margin-right: 8px" @click="closeWin">关闭</Button>
      <Button type="primary" @click="handlerForm">保存</Button>
    </div>
  </Drawer>
</template>

<script>
export default {
  props: {
    modelValue: {type: Boolean, required: true},
    title: {type: String, required: true},
    row: {type: Object, required: true},
  },
  data() {
    return {
      show: this.modelValue,
      formData: {url: this.row.url, linkUrl: this.row.linkUrl, state: this.row.state, id: this.row.id},
      error: {},  // 后端表单校验失败错误信息
      defaultList: this.row.id == null ? [{url: new URL("@/assets/default-user.png", import.meta.url).href}] : [{url: this.$api.previewPath(this.row.url)}],
      uploadList: [],
      ruleValidate: {
        sysId: [
          {required: true, type: "number", message: "系统名不允许为空", trigger: 'change'},
        ],
        url: [
          {required: true, message: "广告图不允许为空", trigger: 'change'},
        ],
        linkUrl: [
          {required: true, message: "链接地址不允许为空", trigger: 'blur'},
          {type: "url", message: "链接地址格式不正确", trigger: 'blur'},
        ],
        state: [
          {type: "boolean", message: "状态必须是一个boolean类型的值", trigger: "blur"}
        ]
      },
      sysList: []
    }
  },
  emits: ["update:model-value", "refresh-data"],
  created(){
    this.$api.queryAllSys().then(ret=> {
      if (ret.data.status) {
        this.sysList = ret.data.list;
        if (this.row.sysId != null) this.formData.sysId = this.row.sysId ;
      }
    })
  },
  methods: {
    handlerForm() {
      // 校验表单参数
      this.$refs.validForm.validate(valid => {
        if (valid) {
          if (this.row.id == null) {
            // 保存
            this.handlerSave();
          } else {
            // 更新
            this.handlerUpdate();
          }
        }
      })
    },
    handleSuccess(response, file, fileList) {
      // 从响应中 获取 上传图片的地址
      file.url = this.$api.previewPath(response.data.url);
      this.formData.url = response.data.url ; // 将后台接口返回的地址赋值给 formData
      this.uploadList = [file];
    },
    handlerSave() {
      this.$api.saveAdvert(this.formData).then(({data:ret})=> {
        if (ret.status) {
          this.$tips.success(ret.message);
          // 刷新数据
          this.$emit("refresh-data") ;
          // 关闭窗口
          this.closeWin() ;
        }else{
          this.error = ret.error ;
        }
      })
    },
    handlerUpdate() {
      this.$api.updateAdvert(this.formData).then(({data:ret})=> {
        if (ret.status) {
          this.$tips.success(ret.message);
          // 刷新数据
          this.$emit("refresh-data") ;
          // 关闭窗口
          this.closeWin() ;
        }else{
          this.error = ret.error ;
        }
      })
    },
    resetValidForm() {
      this.$refs.validForm.resetFields();
    },
    closeWin() {
      this.$emit("update:model-value", false);
    }
  },
  mounted() {
    this.uploadList = this.$refs.upload.fileList;
  },

}
</script>

<style scoped>
.demo-drawer-footer {
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}

.demo-upload-list {
  display: inline-block;
  width: 113px;
  height: 113px;
  text-align: center;
  line-height: 113px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
  margin-right: 4px;
}

.demo-upload-list img {
  width: 100%;
  height: 100%;
}

.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, .6);
}

.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}

.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>